package myschool.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author oldliu
 * @since 1.0
 */
@WebFilter(value = "/*")
public class RoleFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("进入了：RoleFilter");
        try {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String path=request.getServletPath();
            //如下地址是无条件放行
            if(path.equals("/login")||path.equals("/login2.jsp")||path.equals("/doLogin.jsp")||path.equals("/login.jsp")||path.endsWith(".css")){
                filterChain.doFilter(request, servletResponse);
                return;
            }
            Object user = request.getSession().getAttribute("USER_LOGIN");
            if (user == null) {
                request.setAttribute("msg", "您还没登录，不能访问" + request.getServletPath());
                request.getRequestDispatcher("/login2.jsp").forward(request, servletResponse);
                return;
            }
            filterChain.doFilter(request, servletResponse);
        } finally {
            System.out.println("离开了：RoleFilter");
        }

    }

    @Override
    public void destroy() {

    }
}
